package com.zl.tby.core.base.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.IOException;

/**
 * @author changpeng
 * @version 1.0
 * @since 2024/11/3 21:13
 */
public class HttpUtil {
    public static String uploadFile(String url, String filePath) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String responseString = null;

        try {
            httpClient = HttpClients.createDefault();
            HttpPost uploadFile = new HttpPost(url);

            // 设置文件路径
            File file = new File(filePath);

            // 设置multipart的边界
            String boundary = "--------------------------" + System.currentTimeMillis();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setBoundary(boundary);

            // 添加文件部分
            builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());

            // 构建请求实体
            HttpEntity multipart = builder.build();
            uploadFile.setEntity(multipart);

            // 设置请求头
            uploadFile.setHeader("Connection", "keep-alive");
            uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

            // 执行请求
            response = httpClient.execute(uploadFile);

            // 读取响应
            if (response.getEntity() != null) {
                responseString = org.apache.http.util.EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
            responseString = "Error occurred: " + e.getMessage();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseString;
    }

    public static void main(String[] args) {
//        String url = "http://localhost:9100/bz//bz_import_file/upload";
        String url = "http://175.44.137.60:12007/file/upload/img"; // 替换为你的服务器URL
        String filePath = "D:/u418.png";
        String uploadResponse = uploadFile(url, filePath);
        System.out.println("Upload response: " + uploadResponse);
    }
}
